package bb.lanxing.activity.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.ble.BleCons;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseDisplayActivity;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.model.database.Device;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.view.BiciAlertDialogBuilder;

import org.json.JSONObject;
import java.text.DecimalFormat;

import com.github.mikephil.charting.utils.Utils;

public class CrossTrainerStatusActivity extends BaseDisplayActivity implements ConnectionListener {
    private TextView resistanceView;
    private TextView speedView;
    private TextView strideView;
    private TextView steprateView;
    private TextView energyView;
    private TextView distanceView;
    private TextView powerView;
    private Device device;
    private long lastEffectiveTime;
    private TextView nameView;
    private Button unbindBtn;
    private Handler handler = new Handler();
    private static final String DEFAULT_INT = "0";
    private static final String DEFAULT_FLOAT_2 = "0.00";
    private static DecimalFormat decimalFormatFloat2 = new DecimalFormat(DEFAULT_FLOAT_2);
    private static DecimalFormat decimalFormatInt = new DecimalFormat(DEFAULT_INT);

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            if (action.equals(BleCons.ACTION_BATTERY)
                    && intent.getIntExtra(BleCons.EXTRA_DEVICE_TYPE, 0) == SmartDevice.TYPE_CROSS_TRAINER) {
                int intExtra = intent.getIntExtra(BleCons.EXTRA_BATTERY, 0);
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (!DeviceHelper.isConnected(SmartDevice.TYPE_CROSS_TRAINER)) {
            DeviceHelper.connect(this.device);
        } else {
            //requestBattery();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        DeviceHelper.unregisterConnectionStateListener(this);
    }

    /*
    public void requestBattery() {
		this.batteryView.postDelayed(() -> {
            Intent intent = new Intent(BleCons.ACTION_REQUEST_BATTERY);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE, SmartDevice.TYPE_INDOORBIKE);
            IndoorBikeStatusActivity.this.sendOrderedBroadcast(intent, null);
        }, 1000L);
    }
    */

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_cross_trainer_status);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        DeviceHelper.registerConnectionStateListener(this);
        registerReceiver();
        Device byAddress = Device.getByAddress(getIntent().getStringExtra(BleCons.EXTRA_DEVICE_ADDRESS));
        this.device = byAddress;
        if (byAddress == null) {
            finish();
            return;
        }
        this.nameView.setText(byAddress.getName());
        this.unbindBtn.setOnClickListener(view -> CrossTrainerStatusActivity.this.unBoundDeviceConfirm());
    }

    public void unBoundDeviceConfirm() {
        new BiciAlertDialogBuilder(this)
                .setTitle(R.string.st_forget_sensor)
                .setMessage(R.string.st_are_you_sure_unbind)
                .setPositiveButton(R.string.mine_profile_dialog_btn_unbind, (dialogInterface, i) -> {
                    if (CrossTrainerStatusActivity.this.device.getDeviceNumber() > 0) {
                        MyHttpClient.deleteDevice(CrossTrainerStatusActivity.this.device.getDeviceNumber());
                    }
                    Device.deleteAll(Device.class, "address = ? and userId = ?",
                            device.getAddress(), String.valueOf(App.getContext().getUserId()));
                    App.getContext().disconnectDevice(SmartDevice.TYPE_CROSS_TRAINER);
                    DeviceContext.startAndRefreshAutoConnector();
                    CrossTrainerStatusActivity.this.finish();
                })
                .setNegativeButton(R.string.str_sync_cancel, (dialogInterface, i) -> {
                }).show().setCanceledOnTouchOutside(true);
    }

    @Override
    public void onDestroy() {
        DeviceHelper.unregisterConnectionStateListener(this);
        BroadcastReceiver broadcastReceiver = this.broadcastReceiver;
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleCons.ACTION_BATTERY);
        intentFilter.addAction(BleCons.ACTION_CROSSTRAINER_DATAS);
        registerReceiver(this.broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    private void uploadDeivceInfo() {
        MyHttpClient.uploadDevice(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str) {
                try {
                    device.setDeviceNumber(new JSONObject(str).getInt("deviceServerId"));
                    device.save();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, this.device);
    }

    @Override
    protected void onRefreshUI(DisplayPoint displayPoint) {
        String SpeedValue = decimalFormatFloat2.format(displayPoint.getSpeed(Utils.DOUBLE_EPSILON) * 3.6d);
        String DistanceValue = decimalFormatFloat2.format(displayPoint.getCrosstrainerTotalDistance(0)/1000);
        String PowerValue = decimalFormatInt.format(displayPoint.getPower(Utils.FLOAT_EPSILON));
        this.powerView.setText( PowerValue + " " + getString(R.string.unit_power));
        this.speedView.setText(SpeedValue + " " + getString(R.string.unit_km_h));
        this.distanceView.setText(DistanceValue + " " + getString(R.string.unit_km));
        this.strideView.setText(String.valueOf(displayPoint.getCrosstrainerStride(0))+ " " + getString(R.string.unit_stride));
        this.steprateView.setText(String.valueOf(displayPoint.getCrosstrainerSteprate(0))+ " " + getString(R.string.unit_steprate));
        this.energyView.setText(String.valueOf(displayPoint.getCrosstrainerEnergy(0))+ " " + getString(R.string.unit_kcal));
        this.resistanceView.setText(String.valueOf(displayPoint.getCrosstrainerResistanceLevel(0))+ " " + getString(R.string.unit_resistance));
    }

    private void bindView(View view) {
        this.nameView = (TextView) view.findViewById(R.id.nameView);
        this.resistanceView = (TextView) view.findViewById(R.id.resistanceView);
        this.speedView = (TextView) view.findViewById(R.id.speedView);
        this.distanceView = (TextView) view.findViewById(R.id.distanceView);
        this.strideView = (TextView) view.findViewById(R.id.strideView);
        this.steprateView = (TextView) view.findViewById(R.id.steprateView);
        this.energyView = (TextView) view.findViewById(R.id.energyView);
        this.powerView = (TextView) view.findViewById(R.id.powerView);
        this.unbindBtn = (Button) view.findViewById(R.id.unbindBtn);
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
        if (smartDevice.getAddress().equals(this.device.getAddress())) {
            if (i == DeviceManager.STATE_CONNECTED) {
                //this.IndoorBikeView.postDelayed(IndoorBikeStatusActivity.this::requestBattery, 100L);
            } else if (i == DeviceManager.STATE_DISCONNECTED) {
                finish();
            }
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean z) {
        super.onPointerCaptureChanged(z);
    }
}